<template>
  <el-dialog
    v-model="dialogVisible"
    draggable
    :close-on-click-modal="false"
    title="功能管理"
    width="560px"
    center
  >
    <el-form
      ref="formRef"
      :model="formValue"
      :rules="rules"
      label-width="80px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="功能名称" prop="name" required>
        <el-input v-model="formValue.name" placeholder="功能名称"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="功能类别" prop="type" required>
            <el-radio-group v-model="formValue.type">
              <el-radio-button label="菜单"></el-radio-button>
              <el-radio-button label="功能"></el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="formValue.type == '菜单'">
          <el-form-item label="图标" prop="icon">
            <el-select v-model="formValue.icon" clearable filterable>
              <template #prefix v-if="formValue.icon">
                <el-icon color="#666">
                  <component :is="formValue.icon"></component>
                </el-icon>
              </template>
              <el-option v-for="item in icons" :key="item" :label="item" :value="item">
                <el-text>
                  <el-icon>
                    <component :is="item"></component>
                  </el-icon>
                  {{ item }}
                </el-text>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="访问链接" prop="url" v-if="formValue.type == '菜单'">
        <el-input v-model="formValue.url" placeholder="访问链接"></el-input>
      </el-form-item>

      <el-row v-if="formValue.type == '菜单'">
        <el-col :span="12">
          <el-form-item label="组件名称" prop="component">
            <el-input v-model="formValue.component" placeholder="组件名称"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="组件参数" prop="componentParams">
            <el-input v-model="formValue.componentParams" placeholder="组件参数"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="所属父类" prop="parentNo">
            <el-tree-select
              check-strictly
              filterable
              v-model="formValue.parentNo"
              :data="treeList.tree.list"
              :render-after-expand="false"
              placeholder="所属父类"
              clearable
            >
            </el-tree-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="权限" prop="permission">
            <el-input v-model="formValue.permission" placeholder="权限"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="状态" prop="enable">
            <el-switch
              v-model="formValue.enable"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              inline-prompt
              active-text="启用"
              inactive-text="停用"
            ></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示顺序" prop="sort">
            <el-input v-model="formValue.sort" placeholder="排序"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="描述" prop="description">
            <el-input
              type="textarea"
              rows="3"
              v-model="formValue.description"
              placeholder="描述"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <div style="text-align: center" v-has="['menu:add', 'menu:edit']">
        <el-button type="primary" @click="submit(formRef)" auto-insert-space> 保存 </el-button>
        <el-button @click="reset" auto-insert-space>重置</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onActivated } from 'vue'
import type { FormInstance, FormRules, ElMessage, ElMessageBox } from 'element-plus'
import { menugetById, menuSave, menuUpdateById, getSysMenuListTree } from '@/apis/menu.js'

const formRef = ref()

let formValue = ref({
  no: '',
  name: '',
  type: '菜单',
  icon: '',
  url: '',
  component: '',
  componentParams: '',
  permission: '',
  enable: true,
  sort: 100,
  description: '',
  parentNo: ''
})

let rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入功能名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择功能类别', trigger: 'blur' }]
})

let icons = [
  'Plus',
  'Minus',
  'CirclePlus',
  'Search',
  'Female',
  'Male',
  'Aim',
  'House',
  'FullScreen',
  'Loading',
  'Link',
  'Service',
  'Pointer',
  'Star',
  'Notification',
  'Connection',
  'ChatDotRound',
  'Setting',
  'Clock',
  'Position',
  'Discount',
  'Odometer',
  'ChatSquare',
  'ChatRound',
  'ChatLineRound',
  'ChatLineSquare',
  'ChatDotSquare',
  'View',
  'Hide',
  'Unlock',
  'Lock',
  'RefreshRight',
  'RefreshLeft',
  'Refresh',
  'Bell',
  'MuteNotification',
  'User',
  'Check',
  'CircleCheck',
  'Warning',
  'CircleClose',
  'Close',
  'PieChart',
  'More',
  'Compass',
  'Filter',
  'Switch',
  'Select',
  'SemiSelect',
  'CloseBold',
  'EditPen',
  'Edit',
  'Message',
  'MessageBox',
  'TurnOff',
  'Finished',
  'Delete',
  'Crop',
  'SwitchButton',
  'Operation',
  'Open',
  'Remove',
  'ZoomOut',
  'ZoomIn',
  'InfoFilled',
  'CircleCheckFilled',
  'SuccessFilled',
  'WarningFilled',
  'CircleCloseFilled',
  'QuestionFilled',
  'WarnTriangleFilled',
  'UserFilled',
  'MoreFilled',
  'Tools',
  'HomeFilled',
  'Menu',
  'UploadFilled',
  'Avatar',
  'HelpFilled',
  'Share',
  'StarFilled',
  'Comment',
  'Histogram',
  'Grid',
  'Promotion',
  'DeleteFilled',
  'RemoveFilled',
  'CirclePlusFilled',
  'ArrowLeft',
  'ArrowUp',
  'ArrowRight',
  'ArrowDown',
  'ArrowLeftBold',
  'ArrowUpBold',
  'ArrowRightBold',
  'ArrowDownBold',
  'DArrowRight',
  'DArrowLeft',
  'Download',
  'Upload',
  'Top',
  'Bottom',
  'Back',
  'Right',
  'TopRight',
  'TopLeft',
  'BottomRight',
  'BottomLeft',
  'Sort',
  'SortUp',
  'SortDown',
  'Rank',
  'CaretLeft',
  'CaretTop',
  'CaretRight',
  'CaretBottom',
  'DCaret',
  'Expand',
  'Fold',
  'Document',
  'DocumentAdd',
  'Notebook',
  'Tickets',
  'Memo',
  'Collection',
  'Postcard',
  'ScaleToOriginal',
  'SetUp',
  'DocumentDelete',
  'DocumentChecked',
  'DataBoard',
  'DataAnalysis',
  'CopyDocument',
  'FolderChecked',
  'Files',
  'Folder',
  'FolderDelete',
  'FolderRemove',
  'FolderOpened',
  'DocumentCopy',
  'DocumentRemove',
  'FolderAdd',
  'FirstAidKit',
  'Reading',
  'DataLine',
  'Management',
  'Checked',
  'Ticket',
  'Failed',
  'TrendCharts',
  'List',
  'Microphone',
  'Mute',
  'Mic',
  'VideoPause',
  'VideoCamera',
  'VideoPlay',
  'Headset',
  'Monitor',
  'Film',
  'Camera',
  'Picture',
  'PictureRounded',
  'Iphone',
  'Cellphone',
  'VideoCameraFilled',
  'PictureFilled',
  'Platform',
  'CameraFilled',
  'BellFilled',
  'Location',
  'LocationInformation',
  'DeleteLocation',
  'Coordinate',
  'Bicycle',
  'OfficeBuilding',
  'School',
  'Guide',
  'AddLocation',
  'MapLocation',
  'Place',
  'LocationFilled',
  'Van',
  'Watermelon',
  'Pear',
  'NoSmoking',
  'Smoking',
  'Mug',
  'GobletSquareFull',
  'GobletFull',
  'KnifeFork',
  'Sugar',
  'Bowl',
  'MilkTea',
  'Lollipop',
  'Coffee',
  'Chicken',
  'Dish',
  'IceTea',
  'ColdDrink',
  'CoffeeCup',
  'DishDot',
  'IceDrink',
  'IceCream',
  'Dessert',
  'IceCreamSquare',
  'ForkSpoon',
  'IceCreamRound',
  'Food',
  'HotWater',
  'Grape',
  'Fries',
  'Apple',
  'Burger',
  'Goblet',
  'GobletSquare',
  'Orange',
  'Cherry',
  'Printer',
  'Calendar',
  'CreditCard',
  'Box',
  'Money',
  'Refrigerator',
  'Cpu',
  'Football',
  'Brush',
  'Suitcase',
  'SuitcaseLine',
  'Umbrella',
  'AlarmClock',
  'Medal',
  'GoldMedal',
  'Present',
  'Mouse',
  'Watch',
  'QuartzWatch',
  'Magnet',
  'Help',
  'Soccer',
  'ToiletPaper',
  'ReadingLamp',
  'Paperclip',
  'MagicStick',
  'Basketball',
  'Baseball',
  'Coin',
  'Goods',
  'Sell',
  'SoldOut',
  'Key',
  'ShoppingCart',
  'ShoppingCartFull',
  'ShoppingTrolley',
  'Phone',
  'Scissor',
  'Handbag',
  'ShoppingBag',
  'Trophy',
  'TrophyBase',
  'Stopwatch',
  'Timer',
  'CollectionTag',
  'TakeawayBox',
  'PriceTag',
  'Wallet',
  'Opportunity',
  'PhoneFilled',
  'WalletFilled',
  'GoodsFilled',
  'Flag',
  'BrushFilled',
  'Briefcase',
  'Stamp',
  'Sunrise',
  'Sunny',
  'Ship',
  'MostlyCloudy',
  'PartlyCloudy',
  'Sunset',
  'Drizzling',
  'Pouring',
  'Cloudy',
  'Moon',
  'MoonNight',
  'Lightning',
  'ChromeFilled',
  'Eleme',
  'ElemeFilled',
  'ElementPlus',
  'Shop',
  'SwitchFilled',
  'WindPower'
]
const data = [
  {
    value: '1',
    label: '管理员',
    children: [
      {
        value: '1-1',
        label: '普通管理员'
      },
      {
        value: '1-2',
        label: '超级管理员'
      },
      {
        value: '1-3',
        label: '账号管理员'
      }
    ]
  },
  {
    value: '2',
    label: '用户信息',
    children: [
      {
        value: '2-1',
        label: '普通用户'
      },
      {
        value: '2-2',
        label: 'vip用户'
      },
      {
        value: '2-3',
        label: 'svip用户'
      }
    ]
  }
]

let dialogVisible = ref(false)

const emit = defineEmits(['getPage'])

const options = Array.from({ length: 10 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`
}))
let originValue = {}
function open(no) {
  getListTree()

  dialogVisible.value = true

  if (no != undefined && no != null) {
    menugetById({ no })
      .then(function (response) {
        formValue.value = response
        originValue = JSON.parse(JSON.stringify(response))
      })
      .catch(function (error) {
        console.log(error)
      })
  } else {
    let v = {
      no: '',
      name: '',
      type: '菜单',
      icon: '',
      url: '',
      component: '',
      componentParams: '',
      permission: '',
      enable: true,
      sort: 100,
      description: '',
      parentNo: ''
    }

    formValue.value = v
    originValue = JSON.parse(JSON.stringify(v))
  }

  reset()
}

function openTwo(no) {
  getListTree()

  dialogVisible.value = true

  let v = {
    no: '',
    name: '',
    type: '功能',
    icon: '',
    url: '',
    component: '',
    componentParams: '',
    permission: '',
    enable: true,
    sort: 100,
    description: '',
    parentNo: no
  }

  formValue.value = v

  originValue = JSON.parse(JSON.stringify(v))

  reset()
}

function reset() {
  if (!formRef) return
  formRef.value.resetFields()
  formValue.value = JSON.parse(JSON.stringify(originValue))
}

function baoCun() {
  ElMessageBox.confirm('确定要保存吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (formValue.value.no == '') {
        menuSave(formValue.value)
          .then(function (response) {
            if (response) {
              ElMessage({
                type: 'success',
                message: '保存成功'
              })

              dialogVisible.value = false

              emit('getPage')
            }
          })
          .catch(function (error) {
            console.log(error)
          })
      } else if (formValue.value.no != null) {
        menuUpdateById(formValue.value)
          .then(function (response) {
            if (response) {
              ElMessage({
                type: 'success',
                message: '保存成功'
              })

              dialogVisible.value = false
              emit('getPage')
            }
          })
          .catch(function (error) {
            console.log(error)
          })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消保存'
      })
    })
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      baoCun()
    } else {
      console.log('error submit!', fields)
    }
  })
}

let treeList = reactive({
  tree: {
    list: []
  }
})

function getListTree() {
  treeList.tree.list = []
  getSysMenuListTree()
    .then((response) => {
      response.forEach((element) => {
        let obj = {
          value: element.id,
          label: element.name,
          children: []
        }
        if (element.children != undefined && element.children.length > 0) {
          element.children.forEach((children) => {
            obj.children.push({
              value: children.id,
              label: children.name
            })
          })
        }
        treeList.tree.list.push(obj)
      })
    })
    .catch((error) => {
      console.log(error)
    })
}

onActivated(() => {
  // getListTree()
})

defineExpose({ open, openTwo })
</script>

<style lang="scss" scoped></style>
